package com.zone.lib.download.utils;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.zone.lib.download.DownloadConstant;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk_api.ApiManager;
import com.zone.vehicle.sdk.module.superapp.entity.SyncStatusEntity;
import com.zone.vehicle.sdk.module.superapp.request.SyncStatusRequest;

import org.apache.commons.lang3.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

import static com.zone.sdk_api.common.Content.VIN;

/**
 * @Author: pkqlqx
 * @CreateDate: 2021/12/20 21:57
 * @Description:
 */
public class AppStatusUpdateNotify {

    private static final String TAG = AppStatusUpdateNotify.class.getName();

    public static void appNotifyWithoutDownload(Context context, Download mDownload) {
        appNotifyImpl(context, mDownload, true);
    }

    public static void appNotify(Context context, Download mDownload) {
        appNotifyImpl(context, mDownload, false);
    }

    public static void appNotifyImpl(Context context, Download mDownload, boolean withoutDownload) {
        if (ObjectUtils.isEmpty(mDownload)) {
            Log.e(TAG, "error app notify of null download data");
            return;
        }
        Log.d(TAG, "download = " + JSON.toJSONString(mDownload));
        Download temp = DownloadDaoUtilsStore.getInstance().getDownloadByCode(mDownload.getCode());
        if (ObjectUtils.isEmpty(mDownload.getId())) {
            if (ObjectUtils.isNotEmpty(temp)) {
                mDownload.setId(temp.getId());
            }
        }
        if (ObjectUtils.isNotEmpty(temp)) {
            DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().update(mDownload);
        } else if (withoutDownload) {
            DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().insert(mDownload);
            //任务过程中被删除
            Log.e(TAG, "notify but download is delete");
        }
        //发广播
        Intent intent = new Intent();
        intent.setAction(DownloadConstant.APP_STATUS_ACTION);
        intent.putExtra(DownloadConstant.EXTRA_INTENT_APP_STATUS, mDownload);
        context.sendBroadcast(intent);
        if (mDownload.getDownloadStatus() == AppStatusEnum.DOWNLOAD_PAUSE.CODE
                || mDownload.getDownloadStatus() == AppStatusEnum.DOWNLOAD_COMPLETE.CODE
                || mDownload.getDownloadStatus() == AppStatusEnum.DOWNLOAD_FAIL.CODE) {
            //下载任务执行完成，通知控制器更新下载执行队列
            intent.setAction(DownloadConstant.REFRESH_TASK);
            context.sendBroadcast(intent);
        }
        //上报状态
        int process = 0;
        if (mDownload.getAppType().equals(AppTypeEnum.APP.getName()) && mDownload.getSize() > 0) {
            process = (int) ((mDownload.getDownloadLocation() * 100) / mDownload.getSize());
        }
        AppStatusUpdateNotify.sendAppState(mDownload.getAppType(),
                SharedPreferencesUtil.getInstance(context).getSP(VIN),
                SharedPreferencesUtil.getInstance(context).getUserId(context),
                mDownload.getCode(), mDownload.getDownloadStatus(), "" + process, mDownload.getVersion());

    }

    public static void sendAppState(String type, String vin, String userId, String code, int state, String process, String version) {
        SyncStatusEntity entity = new SyncStatusEntity();
        entity.setCode(code);
        entity.setProcess(process);
        entity.setVersion(version);
        entity.setState(state);
        entity.setTime(System.currentTimeMillis());
        uploadAppStatus(type, vin, userId, entity);
    }

    public static void uploadAppStatus(String type, String vin, String userId, SyncStatusEntity entity) {
        if (ObjectUtils.isEmpty(entity)) {
            return;
        }
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(entity.getCode());
        if (ObjectUtils.isEmpty(download)) {
            return;
        }
        SyncStatusRequest request = new SyncStatusRequest();
        request.setType(type);
        request.setVin(vin);
        request.setUserId(userId);
        List<SyncStatusEntity> statusList = new ArrayList<>();
        statusList.add(entity);
        request.setStatusList(statusList);
        Log.d(TAG, "syncStatus request=" + JSON.toJSONString(request));
        ApiManager.getInstance().syncStatus(request, new ResultCallBack<Result>() {
            @Override
            public void onSuccess(Result result) {
                Log.d(TAG, result.toString());
            }

            @Override
            public void onError(String errorCode, String message) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

}
